Import minib3d
Import cal3d

Alias LoadString=mojo.LoadString
#TEXT_FILES="*.txt|*.xml|*.xrf|*.xaf|*.xmf|*.xaf|*.xsf"

Function Main()
	New Game
End



Class Game Extends App

	Field TestModel:Cal3dB3d
	Field cam:TCamera
	Field light:TLight	
	Field init_gl:Bool = False
	Field a:Float=0, dir:Int=0, oldTouchX:Int, oldTouchY:Int, touchBegin:Int, lr#, ud#
	Field txt:TText
	Field dt:DeltaTimer
	
	Method OnCreate()
	


		SetRender()	
		SetUpdateRate 30
		
	End
	
	Method Init()
		
		'If init_gl = true Then Return
		
		dt = New DeltaTimer(30)
		If Not TPixmap.PreLoadPixmap(["mojo_font.png"])	
			Return
		Endif
		cam = CreateCamera()
		cam.CameraClsColor(0,0,80)
		cam.PositionEntity 0,4,-10		
		light=CreateLight(1)
		light.PositionEntity 0,3,-3	
			
		TestModel = New Cal3dB3d
		TestModel.SetSkeleton("monkey://data/paladin/test.xsf")
		TestModel.AddMesh("monkey://data/paladin/testp.xmf")
		TestModel.AddAnim("monkey://data/paladin/run.xaf")
		
		'TestModel.AddAnim("monkey://data/paladin/walk.xaf")
		
		TestModel.Build()	
		If TestModel.CModel.getMixer().blendCycle(0,1,0)
			Print "Execute Run!"
		Endif
		
		
		txt = TText.CreateText2D()	
		Print "main: init done"
		init_gl = True
	End
		
	Method OnUpdate()
	
		
		If KeyHit(KEY_CLOSE) Or KeyHit(KEY_ESCAPE) Then Error ""
		'If init_gl  = True Then
			'Print "Has INIT WTF?"
		'Endif
		'If init_gl = False Then 
		'	Init() 
		'	Return
		'Endif
		dt.UpdateDelta()
		' control camera
		Local cr:Float = KeyDown(KEY_LEFT)-KeyDown(KEY_RIGHT)
		Local cu:Float = KeyDown(KEY_DOWN)-KeyDown(KEY_UP)
		
		Local camin:Float = KeyDown(KEY_W)-KeyDown(KEY_S)
		Local camup:Float = KeyDown(KEY_D)-KeyDown(KEY_A)
		
		Local turnzx:Float = KeyDown(KEY_Z)-KeyDown(KEY_X)
		
		If TouchDown(0) And Not TouchDown(1)
			If Not touchBegin
				oldTouchX = TouchX()
				oldTouchY = TouchY()
				touchBegin = 1
			Endif
			lr = (TouchX() - oldTouchX) * 0.5
			ud = (-TouchY() + oldTouchY) *0.5
			oldTouchX = TouchX()
			oldTouchY = TouchY()
		Elseif TouchDown(1)
			If Not touchBegin
				oldTouchX = TouchX()
				oldTouchY = TouchY()
				touchBegin = 1
			Endif
			camup = (-TouchX() + oldTouchX) * 0.1
			camin = (-TouchY() + oldTouchY) *0.1
			oldTouchX = TouchX()
			oldTouchY = TouchY()
		Else
			touchBegin = 0
		Endif
		
		cam.MoveEntity camup,0,camin
		cam.TurnEntity cu,cr,0
		
		txt.SetText("Cam: "+camup+" "+camin+" "+cu+" "+cr+" delta: "+dt.delta)
		txt.HideEntity()
		txt.Draw(0,0)	
		TestModel.Update(dt.delta/30)
		UpdateWorld()
	End	

	Method OnRender()
		
		RenderWorld()
		
					
	End

End



Class DeltaTimer
	
	Field targetfps:Float = 60
	Field currentticks:Float
	Field lastticks:Float
	Field frametime:Float
	Field delta:Float
	
	Method New (fps:Float)
		targetfps = fps
		lastticks = Millisecs()
	End
	
	Method UpdateDelta:Void ()
		currentticks = Millisecs
		frametime = currentticks - lastticks
		delta = frametime / (1000.0 / targetfps)
		lastticks = currentticks
	End
	
End